import threading
import SocketServer 
import RPi.GPIO as GPIO
from SocketServer import StreamRequestHandler as SRH
from Motor import Motor
import time


M = Motor()

host = '192.168.1.127' 
port = 8888
addr = (host,port)  
	
class Servers(SRH): 
	def handle(self): 
		print 'got connection from ',self.client_address   
		while True:  
			data = self.request.recv(1024)  
			if not data:   
				break  
			else:
				value = 0
				try:
					value = int(data)
					if(value >= 0 and value <= 100):
						print(value)
				except:
                                        M.forward()
                                        time.sleep(0.2)
                                        M.stop()
                                        time.sleep(10)
                                        M.backward()
                                        time.sleep(0.5)
                                        M.stop()
			print data
			print "recv from ", self.client_address[0] 
			self.request.send(data)  
			
def timerfunc():
	global t        #Notice: use global variable!
	t = threading.Timer(0.02, timerfunc)
	t.start()
	
t = threading.Timer(0.02, timerfunc)
t.setDaemon(True)
t.start()

print 'server is running....' 
server = SocketServer.ThreadingTCPServer(addr,Servers)  
server.serve_forever()  
